package com.dsmusic.musicpro.dao;


import com.dsmusic.musicpro.api.JDBCUtils;
import com.dsmusic.musicpro.pojo.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.DecimalFormat;
import java.util.Date;

public class UserDaoImpl implements UserDao2 {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     *
     * @param username 用户名
     * @param password 用户密码
     * @return user 返回所有的信息, 如果没找到，则会返回 null.如果不返回null则说明登录成功，返回null登录失败
     */
    @Override
    public boolean login(String username,String password) {
        try {
            String sql = "select * from user where username = ? and password = ?";
            User user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    username,password);
            return true;
        }catch(DataAccessException e) {
            return false;
        }
    }



    /**
     * 根据用户名查找用户，用户名唯一，如果查找到了就说明已经有同一个用户名了，注册失败
     * @param username 用户名
     * @param password 用户密码
     * @return user 返回所有的信息, 如果没找到，则会返回 null.
     */
    @Override
    public boolean register(String username,String password) {
        User user = null;
        try {
            String sql = "select * from user where username = ?";
            user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<User>(User.class),
                    username);
            return false;
        }catch(DataAccessException e) {
            Date date = new Date();
            //获取最大的uid值
            String sql = "SELECT MAX(uid) FROM `user`";

            Integer key = template.queryForObject(
                    sql,  Integer.class);

            if(key!=null){
                //uid自增
                key++;
            }else{
                key = 0;
            }

            //控制格式为8个长度
            DecimalFormat df = new DecimalFormat("00000000");
            String uid = df.format(key);

            sql = "INSERT INTO `user`(`uid`,`username`,`password`,`logtime`,`regtime`) " +
                    "VALUES(?,?,?,?,?)";
            template.update(sql,
                    uid,
                    username,
                    password,
                    date,
                    date);
            return true;
        }
    }


}
